<?php

namespace App\Http\Controllers\Course;

use App\Events\Message;
use App\Events\Order;
use App\Http\Controllers\BaseController;
use App\Models\Course;
use App\Models\CourseOrder;
use App\Models\User;
use App\Models\UserPointsDetail;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Yansongda\Pay\Pay;

class OrderController extends BaseController
{

    public function index(Request $request)
    {
        $param = $this->validate($request,[
            'sale_type' => 'in:1,2',
            'status' => 'in:1,2'
        ]);

        $user_id = auth('api')->id();
        $query =  CourseOrder::query();

        if (isset($param['sale_type'])){
            $query->where('sale_type',$param['sale_type']);
        }

        if (isset($param['status'])){
            $query->where('status',$param['status']);
        }


        $data = $query->where('user_id',$user_id)->orderByDesc('id')->simplePaginate();

        return $this->success($data);
    }


    public function show(Request $request)
    {
        $param = $this->validate($request,[
            'order_id'=>'required|integer',
        ]);

        $data =  CourseOrder::query()
                    ->where('id',$param['order_id'])
                    ->orderByDesc('id')
                    ->first();

        return $this->success($data);
    }

    public function store(Request $request)
    {
        $param = $this->validate($request,[
            'course_id'=>'required|integer',
            'platform' => 'required|in:1,2,3',
            'pay_method' => 'in:1,2,3'
        ]);


        $course = Course::query()->where('id',$param['course_id'])->first();

        if (empty($course)){
            return $this->error('课程不存在');
        }

        $user = auth('api')->user();

        $data = [
            'user_id' => auth('api')->id(),
            'course_id' => $course->id,
            'sale_type' => $course->sale_type,
            'name' => $course->name,
            'price' => $course->price,
            'points' => $course->points,
            'cover' => $course->cover,
            'trade_no' => getTradeNo(),
            'platform' => $param['platform'],
            'pay_method' => $param['pay_method'] ?? 0,
            'user_income_id' => $course->user_id
        ];


        $course_share_profit = admin_setting_array('course_share_profit');

        $amount = $course->sale_type==1 ? $course->price : $course->points;

        if ($course_share_profit){
            $rate = array_sum(array_values($course_share_profit));

            $data['user_income'] = bcmul((string)$amount,bcdiv((string)(100-$rate),'100',2),2);
            if ($user['parent_id']){
                $data['parent_id'] = $user['parent_id'];
                $data['direct_distribution_income'] = bcmul((string)$amount,(string)($course_share_profit['direct_distribution_rate']/100),2);
                $grand_id = DB::table('users')->where('id',$user['paren_id'])->value('parent_id');
                if ($grand_id){
                    $data['grand_id'] = $grand_id;
                    $data['interposition_income'] =  bcmul((string)$amount,(string)($course_share_profit['direct_distribution_rate']/100),2);
                }
            }

        }

        if ($course->sale_type==2){
            $data['pay_method'] = 3;
        }


        $courseOrder = CourseOrder::query()->create($data);

        switch($course->sale_type){
            case 1:
                $config = config('pay');
                switch ($param['pay_method']){
                    case 1 :
                        $config['wechat']['default']['notify_url'] = 'https://www.huashimu.com/api/course/order/notify';
                        Pay::config($config);
                        $order = [
                            'out_trade_no' => $courseOrder->trade_no,
                            'description' => '广告支付',
                            'amount' => [
                                'total' => (int)bcmul($courseOrder->price,'100'),
                            ],
                        ];
                        $payInfo = '';
                        switch ($param['platform']){
                            case 1:
                                $payInfo =  Pay::wechat()->app($order);
                                break;
                            case 2 :
                                $order['payer']['openid'] = $user['wx_min_openid'];
                                $payInfo = Pay::wechat()->mini($order);
                                break;
                            case 3 :
                                $result = Pay::wechat()->scan($order);
                                $payInfo = ['code_url' => $result->code_url,'trade_no'=> $courseOrder->trade_no];
                                break;
                        }

                        return $this->success($payInfo);
                    case 2 :
                        $config['alipay']['default']['notify_url'] = 'https://www.huashimu.com/api/course/order/ali/notify';
                        $config['alipay']['default']['return_url'] = 'http://www.xn--4pvs78ay6h.xn--fiqs8s/#/school/courseDetail?id='.$param['course_id'];
                        Pay::config($config);
                        if ($param['platform']==1){
                            $aliPay  = Pay::alipay()->app([
                                'out_trade_no' =>  $courseOrder->trade_no,
                                'total_amount' => $courseOrder->price,
                                'subject' => '课程支付',
                            ])->getBody()->getContents();
                        }else{
                            $aliPay  = Pay::alipay()->web([
                                'out_trade_no' =>  $courseOrder->trade_no,
                                'total_amount' => $courseOrder->price,
                                'subject' => '课程支付',
                            ])->getBody()->getContents();
                        }
                        return  $this->success(['payInfo' => $aliPay]);
                }

            case 2:
                if ($course->points>$user['points']){
                    return  $this->error('对不起您的积分不足');
                }
                User::query()->where('id',$user['id'])->decrement('points',$courseOrder->points);
                UserPointsDetail::query()->create([
                    'user_id' => $user['id'],
                    'change_type' => 2,
                    'points' => $courseOrder->points,
                    'remark' => '购买课程扣除'
                ]);

                $courseOrder->status = 2;
                $courseOrder->save();


                event(new Order($user['id']));

                return $this->success();
        }
    }





    public function notify()
    {
        $config = config('pay');
        $config['wechat']['default']['notify_url'] = 'https://www.huashimu.com/api/course/order/notify';

        Pay::config($config);

        $result = Pay::wechat()->callback()->toArray();

        if ($result && $result['event_type'] == 'TRANSACTION.SUCCESS'){
            $order = CourseOrder::query()->where('trade_no',$result['resource']['ciphertext']['out_trade_no'])->first();

            if ($order && $order->status==1){
                $trade_time = date('Y-m-d H:i:s',strtotime($result['resource']['ciphertext']['success_time']));

                event(new Order($order->user_id));
                CourseOrder::query()->where('id',$order->id)->update([
                    'status' => 2,
                    'pay_time' => $trade_time
                ]);

                DB::table('users')
                    ->where('id',$order->income_user_id)
                    ->increment('balance',$order->user_income);
                DB::table('user_balance_details')
                    ->insert([
                        'type' => 3,
                        'source_income_user_id' => $order->user_id,
                        'user_id' => $order->income_user_id,
                        'change_type' => 1,
                        'amount' => $order->user_income,
                        'remark' => '课程收益',
                        'change_time' => date('Y-m-d H:i:s')
                    ]);
                event(new Message([
                    'user_id' => $order->income_user_id,
                    'type' => 4,
                    'content' => '课程余额收益已入账'
                ]));

                event(new \App\Events\Message([
                    'user_id' =>  $order->user_id,
                    'type' => 3,
                    'content' => '你购买的课程已成功支付,课程已解锁!'
                ]));


                if ($order->sale_type==1){
                    if ($order->parent_id && $order->direct_distribution_income>0){
                        DB::table('users')
                            ->where('id',$order->parent_id)
                            ->increment('balance',$order->direct_distribution_income);
                        DB::table('user_balance_details')
                            ->insert([
                                'type' => 4,
                                'source_income_user_id' => $order->income_user_id,
                                'user_id' => $order->parent_id,
                                'change_type' => 1,
                                'amount' => $order->direct_distribution_income,
                                'remark' => '推广收益',
                                'change_time' => date('Y-m-d H:i:s')
                            ]);

                        event(new Message([
                            'user_id' => $order->parent_id,
                            'type' => 4,
                            'content' => '课程推广余额收益已入账'
                        ]));
                    }


                    if ($order->grand_id && $order->direct_distribution_income>0){
                        DB::table('users')
                            ->where('id',$order->grand_id)
                            ->increment('balance',$order->interposition_income);
                        DB::table('user_balance_details')
                            ->insert([
                                'type' =>4,
                                'source_income_user_id' => $order->parent_id,
                                'user_id' => $order->grand_id,
                                'change_type' => 1,
                                'amount' => $order->interposition_income,
                                'remark' => '推广收益',
                                'change_time' => date('Y-m-d H:i:s')
                            ]);

                        event(new Message([
                            'user_id' => $order->grand_id,
                            'type' => 4,
                            'content' => '课程推广余额收益已入账'
                        ]));
                    }

                }else{

                    if ($order->parent_id && $order->direct_distribution_income>0){
                        DB::table('users')
                            ->where('id',$order->parent_id)
                            ->increment('points',(int)$order->direct_distribution_income);
                        DB::table('user_points_details')
                            ->insert([
                                'type' =>4,
                                'source_income_user_id' => $order->income_user_id,
                                'user_id' => $order->parent_id,
                                'change_type' => 1,
                                'points' => (int)$order->direct_distribution_income,
                                'remark' => '推广收益',
                                'change_time' => date('Y-m-d H:i:s')
                            ]);

                        event(new Message([
                            'user_id' => $order->parent_id,
                            'type' => 4,
                            'content' => '课程推广积分收益已入账'
                        ]));
                    }


                    if ($order->grand_id && $order->direct_distribution_income>0){
                        DB::table('users')
                            ->where('id',$order->grand_id)
                            ->increment('points',$order->interposition_income);
                        DB::table('user_points_details')
                            ->insert([
                                'type' =>4,
                                'source_income_user_id' => $order->parent_id,
                                'user_id' => $order->grand_id,
                                'change_type' => 1,
                                'points' => (int)$order->interposition_income,
                                'remark' => '推广收益',
                                'change_time' => date('Y-m-d H:i:s')
                            ]);

                        event(new Message([
                            'user_id' => $order->grand_id,
                            'type' => 4,
                            'content' => '课程推广积分收益已入账'
                        ]));
                    }

                }


                return Pay::wechat()->success();
            }

        }
    }


    public function aliNotify()
    {
        $config = config('pay');
        Pay::config($config);

        $result = Pay::alipay()->callback()->toArray();
        if ($result['trade_status']==='TRADE_SUCCESS'){
            $order = CourseOrder::query()->where('trade_no',$result['out_trade_no'])->first();
            if ($order && $order->status==1){
                event(new Order($order->user_id));
                CourseOrder::query()->where('id',$order->id)->update([
                    'status' => 2,
                    'pay_time' => $result['gmt_payment']
                ]);

                DB::table('users')
                    ->where('id',$order->income_user_id)
                    ->increment('balance',$order->user_income);
                DB::table('user_balance_details')
                    ->insert([
                        'type' => 3,
                        'source_income_user_id' => $order->user_id,
                        'user_id' => $order->income_user_id,
                        'change_type' => 1,
                        'amount' => $order->user_income,
                        'remark' => '课程收益',
                        'change_time' => date('Y-m-d H:i:s')
                    ]);
                event(new Message([
                    'user_id' => $order->income_user_id,
                    'type' => 4,
                    'content' => '课程余额收益已入账'
                ]));

                event(new \App\Events\Message([
                    'user_id' =>  $order->user_id,
                    'type' => 3,
                    'content' => '你购买的课程已成功支付,课程已解锁!'
                ]));


                if ($order->sale_type==1){
                    if ($order->parent_id && $order->direct_distribution_income>0){
                        DB::table('users')
                            ->where('id',$order->parent_id)
                            ->increment('balance',$order->direct_distribution_income);
                        DB::table('user_balance_details')
                            ->insert([
                                'type' => 4,
                                'source_income_user_id' => $order->income_user_id,
                                'user_id' => $order->parent_id,
                                'change_type' => 1,
                                'amount' => $order->direct_distribution_income,
                                'remark' => '推广收益',
                                'change_time' => date('Y-m-d H:i:s')
                            ]);

                        event(new Message([
                            'user_id' => $order->parent_id,
                            'type' => 4,
                            'content' => '课程推广余额收益已入账'
                        ]));
                    }


                    if ($order->grand_id && $order->direct_distribution_income>0){
                        DB::table('users')
                            ->where('id',$order->grand_id)
                            ->increment('balance',$order->interposition_income);
                        DB::table('user_balance_details')
                            ->insert([
                                'type' =>4,
                                'source_income_user_id' => $order->parent_id,
                                'user_id' => $order->grand_id,
                                'change_type' => 1,
                                'amount' => $order->interposition_income,
                                'remark' => '推广收益',
                                'change_time' => date('Y-m-d H:i:s')
                            ]);

                        event(new Message([
                            'user_id' => $order->grand_id,
                            'type' => 4,
                            'content' => '课程推广余额收益已入账'
                        ]));
                    }

                }else{

                    if ($order->parent_id && $order->direct_distribution_income>0){
                        DB::table('users')
                            ->where('id',$order->parent_id)
                            ->increment('points',(int)$order->direct_distribution_income);
                        DB::table('user_points_details')
                            ->insert([
                                'type' =>4,
                                'source_income_user_id' => $order->income_user_id,
                                'user_id' => $order->parent_id,
                                'change_type' => 1,
                                'points' => (int)$order->direct_distribution_income,
                                'remark' => '推广收益',
                                'change_time' => date('Y-m-d H:i:s')
                            ]);

                        event(new Message([
                            'user_id' => $order->parent_id,
                            'type' => 4,
                            'content' => '课程推广积分收益已入账'
                        ]));
                    }


                    if ($order->grand_id && $order->direct_distribution_income>0){
                        DB::table('users')
                            ->where('id',$order->grand_id)
                            ->increment('points',$order->interposition_income);
                        DB::table('user_points_details')
                            ->insert([
                                'type' =>4,
                                'source_income_user_id' => $order->parent_id,
                                'user_id' => $order->grand_id,
                                'change_type' => 1,
                                'points' => (int)$order->interposition_income,
                                'remark' => '推广收益',
                                'change_time' => date('Y-m-d H:i:s')
                            ]);

                        event(new Message([
                            'user_id' => $order->grand_id,
                            'type' => 4,
                            'content' => '课程推广积分收益已入账'
                        ]));
                    }

                }

                return Pay::alipay()->success();
            }

        }
    }


}
